//app.js
require("sdk/libs/strophe");
let WebIM = require("utils/WebIM")["default"];
let disp = require("utils/broadcast");
let logout = false;

App({
  globalData: {
    cutStatus: false, //是否使用图片裁剪工具
    userInfo: null,
    URL: '',
    URLBOOL: '',
    expirationTime: 8*60*60,
    firstURL: 'https://hejianwei.snslearn.com',
    huanxin_msg_user_ids: [], //需要显示环信状态的用户
    hxConfigStatus: false //环信配置展示
  },
  //配置域名地址信息
  configInfo: function(obj = this) {
    var _this = this;
    wx.request({
      url: _this.globalData.firstURL + '/kmapping/WeixinAppAjax/getConfig?lgc=1',
      method: 'GET',
      success: function(res) {
        var _res = res.data;
        if (_res.error_code == 0) {
          for (var key in _res.data) {
            _this.globalData[key] = _res.data[key];
          }
          _this.login(obj);
        }
      }
    })
  },

  //授权登录并向后台发送 res.code 换取 openId, sessionKey, unionId
  login: function(obj = this) {
    var _this = this,
      code = null;
    // 登录
    wx.login({
      success: res => {
        code = res.code;
        var checkToken = wx.getStorageSync('token');
        if (checkToken){
          wx.request({
            url: _this.globalData.URL + '/index.php?app=interface&mod=User&act=checkToken&token=' + checkToken,
            method: 'GET',
            success: function (_res) {
              var res = _res.data;
              if (res.error_code == 0){
                var data = res.data;
                if (data.token_status == 0){
                  if (data.expire_time >= _this.globalData.expirationTime){
                    _this.judgeBind(obj);
                  }else {
                    _this.weixinAppLogin(code, obj);
                  }
                }else {
                  _this.weixinAppLogin(code, obj);
                }
              }
            }
          })
        }else {
          _this.weixinAppLogin(code, obj);
        }
      }
    })
  },

  /**
   * 登陆接口
   */
  weixinAppLogin: function (code, obj){
    var _this = this;
    wx.request({
      url: _this.globalData.URL + '/interface/WeixinApp/login?lgc=1&channel_no=' + wx.getStorageSync('channel_no'),
      data: {
        'code': code,
        'app_name': 'xiaochengxu_eknowme',
        'openid': wx.getStorageSync('openid'),
      },
      method: 'GET',
      success: function (_res) {
        if (_res.data.error_code == 0) {
          wx.setStorageSync('token', _res.data.data.token);
          wx.setStorageSync('openid', _res.data.data.openid);
          wx.setStorageSync('bindAcountBool', _res.data.data.bind_acount_bool);
          wx.setStorageSync('userId', _res.data.data.user_info.uid);
          _this.judgeBind(obj);
        } else {
          _this.rebind();
        }
      }
    })
  },

  /**
   *登录失败重新绑定用户 
   */
  rebind: function() {
    var _this = this;
    var paramStr = '';
    var open_id = wx.getStorageSync('openid');
    if (open_id == false) {
      wx.login({
        success: res => {
          paramStr = 'code=' + res.code;
          _this.noBindAcount(paramStr);
        }
      })
    } else {
      paramStr = 'open_id=' + open_id;
      _this.noBindAcount(paramStr);
    }
  },

  /**
   * 解绑请求
   */
  noBindAcount: function(paramStr) {
    var _this = this;
    wx.request({
      url: _this.globalData.URL + '/interface/WeixinApp/noBindAcount?lgc=1&app_name=xiaochengxu_eknowme&' + paramStr,
      method: 'GET',
      success: function(_res) {
        wx.setStorageSync('bindAcountBool', false);
        _this.login();
      }
    })
  },

  //token失效后重新获取
  setAuth: function(obj = this) {
    wx.openSetting({
      success: (res) => {
        if (res.authSetting["scope.userInfo"]) {
          this.login(obj);
        }
      }
    })
  },

  //授权之后更新用户信息
  setUserInfoAndUpdateInfo: function(user_info) {
    this.globalData.userInfo = user_info;
    wx.request({
      url: this.globalData.URL + '/interface/WeixinApp/updateWeixinAppInfo?user_info=' + JSON.stringify(user_info) + this.globalData.URLBOOL,
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function(res) {
        // console.log(res);
      }
    })
  },

  setGetUserInfo: function(obj = this) {
    var _this = this;
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.userInfo']) {
          wx.authorize({
            scope: 'scope.userInfo',
            success() {
              _this.login(obj);
            },
            fail() {
              // console.log('authSetting1');
            },
            complete() {
              // console.log('authSetting2');
            }
          })
        } else {
          _this.login(obj);
        }
      }
    })
  },

  setUrlBool: function() {
    var user_id = wx.getStorageSync('userId');
    if (!wx.getStorageSync('token')) {
      this.globalData.URLBOOL = 'lgc=1';
    } else {
      this.globalData.URLBOOL = 'token=' + wx.getStorageSync('token') + '&weixin_user_id=' + user_id;
    }
  },

  setAuth: function(obj = this) {
    wx.openSetting({
      success: (res) => {
        if (res.authSetting["scope.userInfo"] == true) {
          this.login(obj);
        } else {}
      }
    })
  },

  //判断是否有token
  judgeToken: function(nowThis, callback) {
    var Token = wx.getStorageSync('token')
    if (Token) {
      if (typeof callback == "function") {
        callback();
      }
    } else {
      this.setAuth(nowThis);
    }
  },

  /**
   * 判断用户账号是否已绑定
   */
  judgeBind: function(obj = this) {
    var bind_acount_bool = wx.getStorageSync('bindAcountBool');
    //如果未绑定，则可选择账号登录
    if (bind_acount_bool == false) {
      wx.reLaunch({
        url: "/pages/bind/bind"
      });
    } else {
      obj.index();
    }
  },

  //匹配url地址http强制改成https
  switchHttp: function(str) {
    return str.replace("http", "https");
  },

  tabbar: {
    color: "#999999",
    selectedColor: "#42d17f",
    backgroundColor: "#ffffff",
    borderStyle: "#d7d7d7",
    list: [{
        type: '1',
        pagePath: "/pages/index/index",
        text: "首页",
        iconPath: "../../images/study.png",
        selectedIconPath: "../../images/selected_study.png",
        selected: true,
        bindtap: ''
      },
      {
        type: '2',
        pagePath: "",
        text: "",
        // iconPath: '../../images/takephoto.png',
        // selectedIconPath: null,
        selected: false,
        bindtap: 'sweepCode'
      },
      {
        type: '1',
        pagePath: "/pages/check/check",
        text: "诊断",
        iconPath: "../../images/check.png",
        selectedIconPath: "../../images/selected_check.png",
        selected: false,
        bindtap: ''
      }
    ],
    position: "bottom"
  },


  changeTabBar: function() {
    var _curPageArr = getCurrentPages();
    var _curPage = _curPageArr[_curPageArr.length - 1];
    var _pagePath = _curPage.__route__;
    if (_pagePath.indexOf('/') != 0) {
      _pagePath = '/' + _pagePath;
    }
    var tabBar = this.tabbar;
    for (let i = 0; i < tabBar.list.length; i++) {
      console.log(_pagePath + '--' + tabBar.list[i].pagePath)
      tabBar.list[i].selected = false;
      if (tabBar.list[i].pagePath == _pagePath) {
        tabBar.list[i].selected = true; //根据页面地址设置当前页面状态  
      }
    }
    _curPage.setData({
      tabbar: tabBar
    });
  },

  /**
   * 扫描条形码
   */
  sweepCode: function() {
    var _this = this,
      user_id = wx.getStorageSync('userId');
    wx.scanCode({
      onlyFromCamera: true, //仅仅相机
      success: (res) => {
        var _result = res.result;
        console.log(_result);
        _result = _result.split("&");
        if (_result[0] != 1101) {
          wx.showToast({
            title: '该套试题未启用!',
            icon: 'none',
            duration: 2000
          })
          _this.sweepCode();
        } else {
          if (_result[0] == 1101) {
            wx.navigateTo({
              url: '/pages/testImg/testImg?online=0&app_id=' + _result[0] + '&paper_download_task_id=' + _result[1] + '&page=' + _result[2] + '&download_task_id=' + _result[3]
            })
          } else if (_result[3] == 1101) {
            wx.navigateTo({
              url: '/pages/testImg/testImg?online=0&app_id=' + _result[3] + '&paper_download_task_id=' + _result[1] + '&page=' + _result[2] + '&download_task_id=' + _result[0]
            })
          }
        }
      },
      //错误返回
      fail: (res) => {
        console.log(res);
      }
    })
  },

  /**
   * 环信登录
   */
  hxlogin: function() {
    var options = {
      apiUrl: WebIM.config.apiURL,
      user: wx.getStorageSync('myUsername'),
      pwd: '888888',
      grant_type: 'password',
      appKey: WebIM.config.appkey //应用key
    }
    WebIM.conn.open(options)
  },

  /**
   * 接受到消息,获取要更新的题目信息；
   */
  dealMessage: function(key, taskId, paperId) {
    var _this = this;
    wx.request({
      url: _this.globalData.URL + '/kmapping/WebAppAjax/getUpdateSsdbTopic?' + _this.globalData.URLBOOL,
      method: 'GET',
      data: {
        key: key
      },
      success: function(res) {
        var _res = res.data;
        if (_res.error_code == 0) {
          _this.dealCache(_res.data.topic_ids, taskId, paperId);
        }
      }
    })
  },

  /**
   * 处理缓存数据
   */
  dealCache: function(topicIds, taskId, paperId) {
    var _this = this,
      user_id = wx.getStorageSync('userId'),
      problemArray = wx.getStorageSync(user_id + '-' + taskId + '-' + paperId),
      pages = getCurrentPages();
    console.log(user_id + '-' + taskId + '-' + paperId);
    console.log(problemArray);
    var onlineAnswer = '',
      answerCard = '';
    for (let i = 0; i < pages.length; i++) {
      if (pages[i].route == 'pages/onlineAnswer/onlineAnswer') {
        onlineAnswer = pages[i];
      }
      if (pages[i].route == 'pages/answerCard/answerCard') {
        answerCard = pages[i];
      }
    }
    if (problemArray) {
      wx.request({
        url: _this.globalData.URL + '/kmapping/WebAppAjax/getTopicStatusBySplitAndTask?' + _this.globalData.URLBOOL,
        method: 'GET',
        data: {
          task_id: taskId,
          paper_ids: paperId
        },
        success(res) {
          if (res.data.error_code == 0) {
            var _problemArray = res.data.data;
            for (var i = 0; i < _problemArray.length; i++) {
              var topics = _problemArray[i].topics;
              for (var j = 0; j < topicIds.length; j++) {
                var split_id = topicIds[j];
                for (var k = 0; k < topics.length; k++) {
                  if (split_id == topics[k].id) {
                    console.log(i);
                    console.log(problemArray[i]);
                    problemArray[i].topics[k] = topics[k]
                  }
                }
              }
            }
            wx.setStorageSync(user_id + '-' + taskId + '-' + paperId, problemArray);
            if (onlineAnswer) {
              onlineAnswer.setData({
                problemArray: problemArray,
                testState: false,
                hxStatus: false
              })
              wx.showLoading({
                title: '试题更新中',
              })
              onlineAnswer.fromCache();
            }
          }
        }
      })
    }
    if (answerCard) {
      wx.request({
        url: _this.globalData.URL + '/kmapping/WebAppAjax/getTopicStatusBySplitAndTask?' + _this.globalData.URLBOOL,
        method: 'GET',
        data: {
          type: 2,
          task_id: taskId,
          paper_ids: paperId
        },
        success(res) {
          if (res.data.error_code == 0) {
            var _problemArray_ac = res.data.data;
            var problemArray_ac = answerCard.data.problemArray;
            for (var i = 0; i < problemArray_ac.length; i++) {
              for (var j = 0; j < _problemArray_ac.length; j++) {
                if (problemArray_ac[i].id == _problemArray_ac[j].id) {
                  var topics = _problemArray_ac[j].topics;
                  for (var x = 0; x < topicIds.length; x++) {
                    var split_id = topicIds[x];
                    for (var k = 0; k < topics.length; k++) {
                      if (split_id == topics[k].id) {
                        problemArray_ac[i].topics[k] = topics[k]
                      }
                    }
                  }
                }
              }
            }
            answerCard.setData({
              problemArray: problemArray_ac
            })
          }
        }
      })
    }

  },

  onLaunch: function() {
    wx.setInnerAudioOption({
      obeyMuteSwitch: false
    })
    var _this = this;
    var logs = wx.getStorageSync("logs") || [];
    logs.unshift(Date.now());
    wx.setStorageSync("logs", logs);

    WebIM.conn.listen({

      /**
       * 重连弹框
       */
      onReconnect() {
        if (_this.globalData.hxConfigStatus) {
          wx.showToast({
            title: "重连中...",
            duration: 2000
          });
        }
      },

      /**
       * socket连接成功弹框
       */
      onSocketConnected() {
        if (_this.globalData.hxConfigStatus) {
          wx.showToast({
            title: "socket连接成功",
            duration: 2000
          });
        }
      },
      /**
       * 网络已断开提示弹框
       */
      onClosed() {
        if (_this.globalData.hxConfigStatus) {
          wx.showToast({
            title: "网络已断开",
            icon: 'none',
            duration: 2000
          });
        }
      },

      onTextMessage: function(message) {
        if (message) {
          var ext = JSON.parse(message.ext.ext);
          console.log(ext);
          if (ext.msg_type == 28) {
            if (_this.globalData.hxConfigStatus) {
              wx.showToast({
                title: '环信收到消息',
                icon: "none",
                duration: 2000
              })
            }
            var messageData = JSON.parse(ext.msg_content);
            var task_id = messageData.task_id,
              paper_id = messageData.resource_id,
              key = messageData.key;
            _this.dealMessage(key, task_id, paper_id);
            //wx.setStorageSync('online-' + _task_id + '-' + _paper_id, problemArray)
          }
        }
      },

      // 各种异常
      onError(error) {
        console.log(error.type)
        // 16: server-side close the websocket connection
        if (error.type == WebIM.statusCode.WEBIM_CONNCTION_DISCONNECTED) {
          if (_this.globalData.hxConfigStatus) {
            wx.showToast({
              title: '服务器连接断开',
              icon: "none",
              duration: 2000
            })
          }
          if (WebIM.conn.autoReconnectNumTotal < WebIM.conn.autoReconnectNumMax) {
            return;
          }
          _this.hxlogin();
          return;
        }
        // 8: offline by multi login
        if (error.type == WebIM.statusCode.WEBIM_CONNCTION_SERVER_ERROR) {
          if (_this.globalData.hxConfigStatus) {
            wx.showToast({
              title: '多登录离线',
              icon: "none",
              duration: 2000
            })
          }
          // _this.hxlogin();
        }

        if (error.type == 'socket_error') { ///sendMsgError
          if (_this.globalData.hxConfigStatus) {
            wx.showToast({
              title: "网络已断开",
              icon: 'none',
              duration: 2000
            });
          }
        }
      },
    })
  }
})